<template>
  <div class="schools-admin">
    <!-- 面包屑导航 -->
    <Breadcrumb />
    
    <div class="page-header">
      <h1>院校管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加院校
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="院校名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入院校名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="所在地区">
          <el-select
            v-model="searchForm.region"
            placeholder="请选择地区"
            clearable
            style="width: 150px"
          >
            <el-option label="杭州市" value="杭州市" />
            <el-option label="宁波市" value="宁波市" />
            <el-option label="温州市" value="温州市" />
            <el-option label="金华市" value="金华市" />
            <el-option label="嘉兴市" value="嘉兴市" />
            <el-option label="绍兴市" value="绍兴市" />
            <el-option label="湖州市" value="湖州市" />
            <el-option label="台州市" value="台州市" />
            <el-option label="丽水市" value="丽水市" />
            <el-option label="衢州市" value="衢州市" />
            <el-option label="舟山市" value="舟山市" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="院校信息" min-width="200">
          <template #default="{ row }">
            <div class="school-info">
              <img 
                :src="row.logo || '/default-school.png'" 
                :alt="row.name"
                class="school-logo"
              />
              <div>
                <div class="school-name">{{ row.name }}</div>
                <div class="school-code">代码：{{ row.code }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="region" label="所在地区" width="120" />
        
        <el-table-column label="联系方式" width="200">
          <template #default="{ row }">
            <div>
              <div>电话：{{ row.phone || '未设置' }}</div>
              <div>邮箱：{{ row.email || '未设置' }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="website" label="官网" width="120">
          <template #default="{ row }">
            <el-link 
              v-if="row.website" 
              :href="row.website" 
              target="_blank" 
              type="primary"
            >
              查看
            </el-link>
            <span v-else>未设置</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-popconfirm
              title="确定要删除这个院校吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="院校名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入院校名称" />
        </el-form-item>
        
        <el-form-item label="院校代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入院校代码" />
        </el-form-item>
        
        <el-form-item label="所在地区" prop="region">
          <el-select v-model="form.region" placeholder="请选择地区" style="width: 100%">
            <el-option label="杭州市" value="杭州市" />
            <el-option label="宁波市" value="宁波市" />
            <el-option label="温州市" value="温州市" />
            <el-option label="金华市" value="金华市" />
            <el-option label="嘉兴市" value="嘉兴市" />
            <el-option label="绍兴市" value="绍兴市" />
            <el-option label="湖州市" value="湖州市" />
            <el-option label="台州市" value="台州市" />
            <el-option label="丽水市" value="丽水市" />
            <el-option label="衢州市" value="衢州市" />
            <el-option label="舟山市" value="舟山市" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="院校地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入院校地址" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="联系邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入联系邮箱" />
        </el-form-item>
        
        <el-form-item label="官网地址" prop="website">
          <el-input v-model="form.website" placeholder="请输入官网地址" />
        </el-form-item>
        
        <el-form-item label="入围公布时间" prop="qualifiedAnnounceTime">
          <el-input v-model="form.qualifiedAnnounceTime" placeholder="如：3月15日" />
        </el-form-item>
        
        <el-form-item label="入围查询链接" prop="qualifiedQueryUrl">
          <el-input v-model="form.qualifiedQueryUrl" placeholder="请输入入围查询链接" />
        </el-form-item>
        
        <el-form-item label="交流群链接" prop="communicationGroupUrl">
          <el-input v-model="form.communicationGroupUrl" placeholder="请输入交流群链接" />
        </el-form-item>
        
        <el-form-item label="院校简介" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入院校简介"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createSchool, updateSchool, deleteSchool, getSchoolList } from '@/api/school'

// 搜索表单
const searchForm = reactive({
  name: '',
  region: '',
  status: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 弹窗
const dialogVisible = ref(false)
const dialogTitle = computed(() => form.id ? '编辑院校' : '添加院校')
const submitLoading = ref(false)

// 表单
const formRef = ref()
const form = reactive({
  id: null,
  name: '',
  code: '',
  region: '',
  address: '',
  phone: '',
  email: '',
  website: '',
  qualifiedAnnounceTime: '',
  qualifiedQueryUrl: '',
  communicationGroupUrl: '',
  description: '',
  status: 1
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入院校名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入院校代码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    
    // 模拟数据，实际应该调用API
    const mockData = {
      data: {
        list: [
          {
            id: 1,
            name: '浙江工业职业技术学院',
            code: '12871',
            region: '绍兴市',
            address: '绍兴市越城区梅山路建功路',
            phone: '0575-88009063',
            email: 'zsjy@zjitc.edu.cn',
            website: 'http://www.zjitc.edu.cn',
            description: '浙江工业职业技术学院是经浙江省人民政府批准设立的公办高等职业院校',
            status: 1,
            createTime: new Date('2024-01-15'),
            logo: '/default-school.png'
          },
          {
            id: 2,
            name: '宁波职业技术学院',
            code: '12863',
            region: '宁波市',
            address: '宁波市北仑区新碶庐山东路388号',
            phone: '0574-86891301',
            email: 'zsb@nbpt.edu.cn',
            website: 'http://www.nbpt.edu.cn',
            description: '宁波职业技术学院是1999年由教育部批准成立的从事高等职业教育的全日制普通高校',
            status: 1,
            createTime: new Date('2024-01-10'),
            logo: '/default-school.png'
          }
        ],
        total: 47
      }
    }
    
    tableData.value = mockData.data.list
    pagination.total = mockData.data.total
  } catch (error) {
    ElMessage.error('获取院校列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    region: '',
    status: null
  })
  handleSearch()
}

// 添加
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessageBox.alert(row.description || '暂无简介', row.name, {
    confirmButtonText: '确定'
  })
}

// 删除
const handleDelete = async (row) => {
  try {
    // await deleteSchool(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    // await updateSchool({ id: row.id, status: row.status })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (form.id) {
      // await updateSchool(form)
      ElMessage.success('更新成功')
    } else {
      // await createSchool(form)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    region: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    qualifiedAnnounceTime: '',
    qualifiedQueryUrl: '',
    communicationGroupUrl: '',
    description: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getList()
}

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${d.getFullYear()}-${month}-${day}`
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.schools-admin {
  padding: 24px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
  
  .table-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    .school-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .school-logo {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        object-fit: cover;
      }
      
      .school-name {
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .school-code {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .schools-admin {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h1 {
        font-size: 20px;
      }
    }
    
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          display: block;
          margin-bottom: 16px;
        }
      }
    }
    
    .table-card {
      :deep(.el-table) {
        font-size: 12px;
      }
    }
  }
}
</style>